<script setup lang="ts">
import type { todoItem } from "./index";
import { formDate } from "@/utils/tools";
import { ref } from "vue";
const title = ref<string>("");
const todoList = ref<todoItem[]>([]);
// 新增
const addNewItem = (): void => {
  todoList.value.push({
    title: title.value,
    id: Math.random().toString(36).substring(2, 12),
    timeStamp: formDate(),
    edit: false,
  });
  title.value = "";
};
// 删除
const deleItem = (i: string): void => {
  todoList.value = todoList.value.filter((it) => it.id !== i);
};
// 置顶
const moveItemToNumberOne = (it: todoItem, i: number): void => {
  if (i == 0) return alert("当前为第一条");
  const tempIndex = todoList.value.findIndex((i) => i.id == it.id);
  const temObj = todoList.value[0];
  todoList.value[0] = it;
  todoList.value[tempIndex] = temObj;
};
// 编辑
const editItem = (i: todoItem): void => {
    i.edit = true
};
// 保存
const handleBlur = (e:FocusEvent,i:todoItem):void => {
    i.edit = false
}
</script>
<template>
  <div class="listContainer">
    <div class="header">
      <input v-model="title" class="inputArea" type="text" />
      <div class="search" @click="addNewItem">新增</div>
    </div>
    <div class="listBody">
      <div class="list" v-for="(item, i) in todoList" :key="item.id">
        <div class="indexNumber">{{ i + 1 }}</div>
        <div class="time">{{ item.timeStamp }}</div>
        <div class="todo">
          <span v-if="!item.edit">{{ item.title }}</span
          ><input type="text" v-else v-model="item.title" @blur="handleBlur($event,item)"/><span></span>
        </div>
        <div class="operation">
          <button @click="deleItem(item.id)">❌删除</button>
          <button @click="moveItemToNumberOne(item, i)">👆置顶</button>
          <button @click="editItem(item)">🖍编辑</button>
        </div>
      </div>
    </div>
    <div class="footer" v-if="todoList?.length">
      共计 {{ todoList.length }} 条
    </div>
  </div>
</template>
<style scoped>
.listContainer {
  width: 60vw;
  height: 60vh;
  /* background: orange; */
  position: absolute;
  top: 50vh;
  left: 50vw;
  transform: translate(-50%, -50%);
  box-sizing: border-box;
  border: 1px solid #999;
  display: flex;
  flex-direction: column;
}
.header {
  height: 40px;
  margin-bottom: 10px;
}
.header .inputArea,
.search {
  height: 100%;
  display: inline-block;
  box-sizing: border-box;
}
.inputArea {
  outline: none;
  /* border: none; */
  width: 30%;
  border-radius: 0;
  box-shadow: none;
}
.search {
  padding: 4px 20px;
  line-height: 30px;
  background: pink;
  color: white;
  cursor: pointer;
}

.listBody {
  flex-grow: 1;
}
.list {
  width: 100%;
  display: flex;
  border: 1px solid #cfcfcf;
}
.list > div {
  width: 25%;
  position: relative;
  min-height: 40px;
}
.list .operation {
  display: flex;
  align-items: center;
}
</style>